#include <stdio.h>
#include "rwlock_freertos.h"

void rwlock_init(rwlock_t *lock)
{
    lock->read_mutex = xSemaphoreCreateMutex();
    lock->write_mutex = xSemaphoreCreateMutex();
    lock->readers_count = 0;
    lock->initialized = 1;
}

void rwlock_lock_read(rwlock_t *lock)
{
    xSemaphoreTake(lock->read_mutex, portMAX_DELAY);
    lock->readers_count++;
    if (lock->readers_count == 1)
    {
        xSemaphoreTake(lock->write_mutex, portMAX_DELAY);
    }
    xSemaphoreGive(lock->read_mutex);
}

void rwlock_unlock_read(rwlock_t *lock)
{
    xSemaphoreTake(lock->read_mutex, portMAX_DELAY);
    lock->readers_count--;
    if (lock->readers_count == 0)
    {
        xSemaphoreGive(lock->write_mutex);
    }
    xSemaphoreGive(lock->read_mutex);
}

void rwlock_lock_write(rwlock_t *lock)
{
    xSemaphoreTake(lock->write_mutex, portMAX_DELAY);
}

void rwlock_unlock_write(rwlock_t *lock)
{
    xSemaphoreGive(lock->write_mutex);
}

void rwlock_destroy(rwlock_t *lock)
{
    if (lock->read_mutex != NULL)
    {
        vSemaphoreDelete(lock->read_mutex);
        lock->read_mutex = NULL;
    }
    if (lock->write_mutex != NULL)
    {
        vSemaphoreDelete(lock->write_mutex);
        lock->write_mutex = NULL;
    }
    lock->destroyed = 1;
}
